package edu.assignment2;

import java.util.ArrayList;
import java.util.List;

import lpsolve.LpSolve;
import lpsolve.LpSolveException;
import edu.aa12.BnBNode;
import edu.aa12.Edge;
import edu.aa12.Graph;

public class LpMaximumRadius {

	private Graph graph;
	private BnBNode node;
	private List<Edge> excludedEdges;

	public LpMaximumRadius(Graph graph, BnBNode node) {
		this.graph = graph;
		this.node = node;
		this.excludedEdges = new ArrayList<Edge>();
	}

	public double getSolution() {
		BnBNode n = node;

		double result = 0.0;

		while (n.parent != null) {
			if (!n.edgeIncluded)
				excludedEdges.add(n.edge);
			n = n.parent;
		}

		try {
			LpSolve solver = LpSolve.makeLp(0, graph.getVertices());

			double[] vars = new double[graph.getVertices()];
			for (int i = 0; i < vars.length; i++) {
				vars[i] = 1.0;
			}

			solver.setObjFn(vars);

			for (Edge edge : graph.edges) {
				if (!excludedEdges.contains(edge)) {
					vars = new double[graph.getVertices()];
					vars[edge.u] = vars[edge.v] = 1.0;
					solver.addConstraint(vars, LpSolve.LE,
							graph.getLength(edge));
				}
			}

			solver.setMaxim();

			solver.setVerbose(LpSolve.IMPORTANT);

			solver.solve();

			result = solver.getObjective();

			solver.deleteLp();
		} catch (LpSolveException e) {
			e.printStackTrace();
		}
		return result;
	}
}
